package com.ys.fmms.controller;

import com.alibaba.excel.EasyExcel;
import com.ys.fmms.pojo.DataDisplay;
import com.ys.fmms.service.DataDisplayService;
import com.ys.fmms.util.Result;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("/fmms/dataDisplayController")
@Api(tags = "处理展示的数据的导入导出")
public class DataDisplayController {
    @Autowired
    private DataDisplayService dataDisplayService;

    @Operation(summary = "导出excel")
    @GetMapping(value = "/exportExcel")
    public void getCurrentExcel(HttpServletResponse response) {
        // 获取要导出的excel数据
        List<DataDisplay> dataDisplayList = dataDisplayService.getList();
        // 设置内容类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        // 设置字符编码
        response.setCharacterEncoding("utf-8");
        String fileName = "data";
        // 设置响应头 以下载方式打开
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        try {
            EasyExcel.write(response.getOutputStream(), DataDisplay.class).sheet("数据").doWrite(dataDisplayList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Operation(summary = "导入excel")
    @PostMapping("/importExcel")
    public Result uploadExcel(@RequestPart(value = "file") MultipartFile multipartFile) {
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            dataDisplayService.uploadData(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.myFail(null).message("上传失败");
        }
        return Result.ok();
    }
}
